package cn.springcloud.fix.common.core.storage;

import cn.springcloud.fix.common.core.storage.impl.AliYunFileStorage;
import cn.springcloud.fix.common.core.storage.impl.LocalFileStorage;
import cn.springcloud.fix.common.core.storage.properties.LocalStorageProperties;
import cn.springcloud.fix.common.core.storage.properties.OssProperties;
import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@EnableConfigurationProperties({OssProperties.class, LocalStorageProperties.class})
public class StorageAutoConfiguration {

    @Autowired
    private OssProperties ossProperties;

    @Autowired
    private LocalStorageProperties localStorageProperties;

    /**
     * 根据配置文件自动装配阿里云SSO存储组件
     */
    @Bean
    @ConditionalOnProperty(prefix = "cloud.storage", name = "type", havingValue = "aliyun")
    @ConditionalOnMissingBean(FileStorage.class)
    @Order(0)
    public AliYunFileStorage aliyunFileStorage() {
        OSSClient ossClient = new OSSClient(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        return new AliYunFileStorage(ossClient, ossProperties.getBucketName());
    }

    /**
     * 根据配置文件自动装配本地存储组件
     */
    @Bean
    @ConditionalOnProperty(prefix = "cloud.storage", name = "type", havingValue = "local")
    @ConditionalOnMissingBean(FileStorage.class)
    @Order(1)
    public LocalFileStorage localFileStorage() {
        return new LocalFileStorage(localStorageProperties.getLocation());
    }

    /**
     * 默认配置用户目录作为存储目录
     */
    @Bean
    @Order(2)
    @ConditionalOnMissingBean(FileStorage.class)
    public LocalFileStorage defaultLocalStorage() {
        return new LocalFileStorage(System.getProperty("user.home"));
    }
}
